package com.ghsc.ghxc.jsb.ui.my.activity

import android.os.Message
import android.text.TextUtils
import android.view.View
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityOrderDetailBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ext.setOnFastClickListener
import com.ghsc.ghxc.jsb.ui.my.bean.OrderDetailBean
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.activity
 * 类名：OrderDetailActivity
 * 创建时间：2024/4/25 22:54
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 订单详情
 */
class OrderDetailActivity : BaseVMActivity<OrderListViewModel, ActivityOrderDetailBinding>(){
    override fun attachVMClass(): Class<OrderListViewModel> = OrderListViewModel::class.java

    override fun attachLayoutRes() = R.layout.activity_order_detail
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    private val oid: String by intentExtras("oid","0")
    private var orderDetailBean: OrderDetailBean?= null
//    private val mAdapter: KdInfoListAdapter by lazy { KdInfoListAdapter() }
//    var mList = arrayListOf<KdInfoBean>()


    override fun initView() {
        binding.apply {
            bar.topTitle.text = "订单详情 "
            bar.topLeftView.setOnClickListener { finish() }
        }

        binding.apply {
            tvHome.setOnClickListener { finish() }
            stvCopy.setOnFastClickListener {
//                orderDetailBean?.let {
//                    copyToClipboard(this@OrderDetailActivity,it.oid)
//                }
            }
            stvLogisticsCopy.setOnFastClickListener {
//                orderDetailBean?.let {
//                    copyToClipboard(this@OrderDetailActivity,"${it.kdname}\r\n${it.kdno}","快递单号已复制")
//                }
            }
        }
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustKey.WECHAT_PAY_SUCCESS && rxBusBean.sign == CustKey.WECHAT_PAY_SUCCESS) {
                    val isSuccess = rxBusBean.anyBean.toString().toBoolean()
                    if (isSuccess){
                        showToast("支付成功")
                    }else{
                        showToast("支付失败")
                    }
                    //刷新接口
                    initData()
                }else if (rxBusBean.id == CustKey.CHECK_PAY_RESULT && rxBusBean.sign == CustKey.CHECK_PAY_RESULT) {
                    //刷新接口
                    initData()
//                        orderDetailBean?.let {
//                            if (it.status == "待支付"){
//                                val map: HashMap<String, Any> = HashMap()
//                                map["oid"] = oid.toString()
//                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.checkPayOrder(it1) }
//                            }
//                        }
                }
            }
        initRefreshLayout()

    }
    private fun initRefreshLayout() {
        binding.refreshLayout.setEnableLoadMore(false)
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                initData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {

            }
        })
    }
    override fun initData() {
        super.initData()
        val map: HashMap<String, Any> = HashMap()
        map["oid"] = oid.toString()
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.orderDetail(it1) }
    }
    fun  getKdData(){
//        orderDetailBean?.let {
//            val map: HashMap<String, Any> = HashMap()
//            map["kdno"] = it.kdno
//            map["mobile"] = it.shouhuo_mobile
//            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onOrderDetailKuaidiInfo(it1) }
//        }
    }
    var isCut=true  //是否正常拉起
    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            delay(1000) // 延时1秒
            // 在这里执行需要延时的操作
            if (!isCut){
                initData()
            }
        }

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            stvpay.setSingleClickListener {
                showToast("暂时无法支付")
            }
            stvTuiKuanCancel.setSingleClickListener {
                //退款
                XPopup.Builder(this@OrderDetailActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@OrderDetailActivity,"提示","确定要退款吗?",
                            btnConfirm={
                                val map: HashMap<String, Any> = HashMap()
                                map["oid"] = oid
                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShenqingTuikuan(it1) }
                            },
                            btnCancel={
                            },)
                    )
                    .show()
            }
            stvTuiKuan.setSingleClickListener {
                //退款
                XPopup.Builder(this@OrderDetailActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@OrderDetailActivity,"提示","确定要退款吗?",
                            btnConfirm={
                                val map: HashMap<String, Any> = HashMap()
                                map["oid"] = oid
                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShenqingTuikuan(it1) }
                            },
                            btnCancel={
                            },)
                    )
                    .show()
            }
            stvSub.setSingleClickListener {
                XPopup.Builder(this@OrderDetailActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@OrderDetailActivity,"提示","请您检查商品无误后再点击确认收货！确认收货后平台不支持退货退款哦",
                            btnConfirm={
                                val map: HashMap<String, Any> = HashMap()
                                map["oid"] = oid
                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onQuerenShouhuo(it1) }
                            },
                            btnCancel={
                            },)
                    )
                    .show()
            }

        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        binding.apply {
            mViewModel.apply {
                errorMsg.observe(this@OrderDetailActivity) {
                    binding.refreshLayout.finishRefresh()
                    showToast(it)
                }
                againLoginMsg.observe(this@OrderDetailActivity) {
                    binding.refreshLayout.finishRefresh()
                    showToast(CustKey.IN_AGAIN_MSG)
                    LoginHelper.startLoginPage()
                }
                orderDetailResult.observe(this@OrderDetailActivity){
                    binding.refreshLayout.finishRefresh()

                    it.data.data.let {
                        orderDetailBean = it
                        tvName.text = "${it.shouhuo_name} ${it.shouhuo_mobile}"
                        tvAddress.text = "${it.shouhuo_site}"
                        //
                        GlideUtil.ImageLoad(this@OrderDetailActivity,it.skuimages,ivOrderImg)
                        tvOrderName.text = it.title
                        tvOrderCategory.text=it.skuvalue
                        tvPrice.text = "¥${it.price}"
                        tvOrderCount.text = "x${it.cnt}"
                        //
                        tvOrderNumber.text = "${it.oid}"
                        tvCreateTime.text = "${it.crt_time}"
                        tvOrderState.text = "${it.status}"
                        tvPayWay.text = "${it.pay_type}"
                        tvYunFei.text = "¥${it.yunfei}"
                        tvPriceTotal.text = "¥${it.skuprice}"

                        if(it.status=="待支付") {
                            sclPay.visible()
                            sclShippedGoods.gone()
                            tvPayRmb.text = "¥${it.skuprice}"
                        }else {
                            sclPay.gone()
                            sclShippedGoods.visible()
                            if(it.status == "待发货"){
                                stvTuiKuan.visible()
                                stvTuiKuan.text="退 款"
                            }else{
                                stvTuiKuan.gone()
                            }
                            if(it.status == "待收货"){
                                stvSub.visible()
                                stvSub.text="确认收货"
                            }else{
                                stvSub.gone()
                            }
                            if(it.status == "退款失败"){
                                stvTuiKuanCancel.visible()
                                stvTuiKuanCancel.text="申请退款"
                            }else{
                                stvTuiKuanCancel.gone()
                            }
                        }
                    }

                    getKdData();
                }
                cancelOrderResult.observe(this@OrderDetailActivity){
                    showToast("订单已取消")
                    finish()
                }
                onTixingFahuo.observe(this@OrderDetailActivity){
                    showToast("已提醒发货")
                    binding.refreshLayout.autoRefresh()
                }
                //确认收货
                onQuerenShouhuo.observe(this@OrderDetailActivity){
                    showToast("确认收货成功")
                    binding.refreshLayout.autoRefresh()
                }
                onShenqingTuikuan.observe(this@OrderDetailActivity){
                    showToast("申请成功")
                    binding.refreshLayout.autoRefresh()
                }
            }
        }
    }
}